/**
 *  The Yz.Form class
 */
(function(Yz) {
    if ( typeof(Yz) != "function" ) {
        throw "Failed to identify the root Yz object";
    }

    // prevent multiple execution
    if ('Form' in Yz && 'Category' in Yz.Form) {
        return;
    }

    // TODO actually extend Form.element
    Yz.Form.Category = function(form, elName, loadURL)
    {
        if (elName in form.elements)
            return form.elements[elName];
        if (! loadURL)
            throw "Argument loadURL can not be empty";
        this.loadURL = loadURL;
        Yz.Form.Element.apply(this, [form, elName]);
    }


    /****************************
     *      Implementation      *
     ****************************/

    Yz.Form.Category.prototype = {

        loadURL: "",
        elementDiv: null,   // the form element's enclosing DIV
        a_select: null,     // the 'Select category' anchor
        value: null,
        clicked: null,

        init: function() {
            console.log("init: creating Form.Category " + this.name);
            this.elementDiv = $('#FormElement_' + this.name);
            this.formElement = $('input[name=' + this.name + ']');
            this.value = parseInt(this.formElement.val());

            // click handler for path 'links'
            var self = this;
            this.clicked = function() {
                // 'this' will be the HTML element
                return self.load(this)
            }

            // first, assign click handler to 'select category'
            this.a_select = this.elementDiv.find('a._select').click(this.clicked);

            //$(function() {
                if (self.value > 0) {
                    console.log('category value=' + self.value)
                    // assign click handler to all category path entries
                    self.elementDiv.find('a._category').click(self.clicked);
                    // make those appear as clickable links
                    self.elementDiv.find('._path').removeClass('_value');
                    // hide 'select category'
                    self.a_select.hide()
                } else {
                    console.log('category value is empty')
                    // no categories nor path present: load categories[catId=0]
                    self.load(self.a_select.get(0))
                }
            //});
        },
        /** Click handler for link to 'category' (css class: _category)
        *  @param HTMLAnchorElement a_category
        */
        load: function(a_category)
        {
            console.log("load: url='"+this.loadURL+"'")
            var href = a_category.getAttribute("href");
            var catId = href.match(/\d+$/);
            catId = catId ? catId[0] : 0;
            console.log("load: catId='"+catId+"'")
            var self = this;
            this.elementDiv.find('._children').load(
                this.loadURL + catId,
                null,
                function() {
                    // 'this' is the _children element
                    self.onload(this, a_category, catId)
                }
            ).show();
            return false;
        },

        /**
         *  @param divChildren
         *  @param a_category the anchor that was clicked
         *  @param catId the category id to load
         *
         */
        onload: function(divChildren, a_category, catId)
        {
            // set the selected value
            var oldValue = this.value;
            this.value = catId;
            this.formElement.val(catId);

            // setup onclick callbacks for the newly fetched 'link' elements
            var self = this;
            $(divChildren).find('a').click(self.clicked);

            var divPath = this.elementDiv.find('._path');

            if (! catId) {
                // if empty category selected,
                // clear the path
                divPath.html(); // '<span> &raquo;</span> '
                // show 'select category' link and return
                this.a_select.show()
                return
            }

            this.a_select.hide()

            var catLink;
            // if the anchor clicked is in the 'path'
            if (a_category.parentNode.className.indexOf('_path') != -1)
                catLink = $(a_category)
            else
                catLink = divPath.find('a[href="#' + catId + '"]')

            if (catLink.length > 0) {
                catLink.next().nextAll().remove();
            } else {
                // take category 'link' from the loaded list,
                // set the correct href
                // and add to path div
                $(a_category)
                    .attr('href', '#' + catId)
                    .click(self.clicked)
                    .appendTo(divPath)
                divPath.append('<span> &raquo;</span> ')
            }
        }
    }

})(window.Yz);
